import { createRouter, createWebHashHistory } from "vue-router";
import useStore from "@/store";
// 布局组件不用路由懒加载   路由懒加载也叫异步组件
import Layout from "@/views/layout/index.vue";
import Home from "@/views/home/index.vue";

const router = createRouter({
  // 匹配模式
  history: createWebHashHistory(),
  // 页面的滚动行为
  scrollBehavior(to, from, savedPosition) {
    // 始终滚动到顶部
    return { top: 0 };
  },
  // 规则
  routes: [
    {
      path: "/",
      component: Layout,
      children: [
        {
          path: "",
          component: Home,
        },
        {
          path: "category/:id",
          component: () => import("@/views/category/index.vue"),
        },
        {
          path: "category/sub/:id",
          component: () => import("@/views/category/sub.vue"),
        },
        {
          path: "goods/:id",
          component: () => import("@/views/goods/index.vue"),
        },
        {
          path: "/cart",
          component: () => import("@/views/cart/index.vue"),
        },
        {
          path: "/member/checkout",
          component: () => import("@/views/member/pay/checkout.vue"),
        },
      ],
    },
    { path: "/login", component: () => import("@/views/login/index.vue") },
    {
      path: "/login/callback",
      component: () => import("@/views/login/callback.vue"),
    },
    { path: "/demo", component: () => import("@/views/demo/index.vue") },
  ],
});

// 配置路由导航守卫，拦截 /member开头的所有的地址
router.beforeEach((to, from, next) => {
  const { cart } = useStore();
  if (cart.isLogin) {
    next();
  } else {
    if (to.path.includes("/member")) {
      next({
        path: "/login",
        query: {
          redirectUrl: to.fullPath,
        },
      });
    } else {
      next();
    }
  }
});
export default router;
